package org.lzuploader.gui.listeners.servers;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Shell;
import org.lzuploader.controller.NetTester;
import org.lzuploader.exception.ThreadAlreadyRunningException;
import org.lzuploader.gui.WServers;
import org.lzuploader.gui.WWait;
import org.lzuploader.gui.helpers.EasyMessageBox;
import org.lzuploader.model.Constants;
import org.lzuploader.model.Localization;

/** This class is used when a user wants to test the connection to a server.
 * 
 * @author Emmanuel Cron
 *
 */
public class TestSelectionListener implements SelectionListener
{
    /** The logger for this class. */
    private static Log log = LogFactory.getLog(TestSelectionListener.class);
    
    /** Localization of this class. */
    private Localization localization = Localization.getInstance();
    
    /** Used when the widget is selected by default.
     * @param e The associated event
     */
    @Override
    public void widgetDefaultSelected(final SelectionEvent e)
    {
        widgetSelected(e);
    }

    /** Used when the user clicked on the widget.
     * @param e The associated event
     */
    @Override
    public void widgetSelected(final SelectionEvent e)
    {
        log.debug("Testing connection to server.");
        
        log.trace("Fetching data.");
        
        Shell wServersShell = null;
        for (int i = 0 ; i < e.display.getShells().length ; i++)
        {
            if (e.display.getShells()[i].getData() instanceof WServers)
            {
                wServersShell = e.display.getShells()[i];
                break;
            }
        }
        
        final WServers servers = (WServers) wServersShell.getData();
        final String name = servers.getNameWidget().getText();
        final String server = servers.getServerWidget().getText();
        final int port = servers.getPortWidget().getSelection();
        final StringBuffer path = new StringBuffer(servers.getPathWidget().getText());
        
        log.trace("Checking if all data have been filled.");
        
        if (name.length() == 0 || server.length() == 0 || path.length() == 0)
        {
            log.trace("At least one data is missing. Displaying error and returning.");
            
            EasyMessageBox.info(
                localization.getString("DIALOG_TITLE_INFO"),
                localization.getString("DIALOG_REQUIRE_ALL_FIELDS")
            );
            return;
        }
        
        log.debug("All data OK. Connecting and reading page.");
        
        if (path.charAt(path.length() - 1) != '/')
        {
            path.append("/");
        }
        path.append(Constants.NET_UPLOAD_PAGE);
        
        log.trace("Displaying wait window");
        
        final WWait wait = WWait.getInstance();
        
        try
        {
            wait.begin(wServersShell);
        }
        catch (final ThreadAlreadyRunningException tare)
        {
            log.error("A waiting window is already running, I cannot continue until it is closed.");
            
            EasyMessageBox.error(
                localization.getString("DIALOG_TITLE_ERROR"),
                localization.getString("DIALOG_PROCESS_ALREADY_RUNNING")
            );
            
            return;
        }
        
        log.trace("Creating & starting tester.");
        
        final NetTester tester = new NetTester(server, port, path.toString());
        tester.start();
        
        wait.reset();
        
        long timer = System.currentTimeMillis();
        while (tester.isAlive())
        {
            if (System.currentTimeMillis() - timer > 100)
            {
                wait.step();
                timer = System.currentTimeMillis();
            }
            
            if ( wServersShell.getDisplay().readAndDispatch() == false)
            {
                wServersShell.getDisplay().sleep();
            }
        }
        
        wait.finish();
        
        if (tester.hasMessage())
        {
            if (tester.getLastMessage().isError())
            {
                EasyMessageBox.error(
                    tester.getLastMessage().getTitle(),
                    tester.getLastMessage().getContents()
                );
            }
            else if (tester.getLastMessage().isInfo())
            {
                
                log.trace("Test successful, enabling add button.");
                
                EasyMessageBox.info(
                    tester.getLastMessage().getTitle(),
                    tester.getLastMessage().getContents()
                );
                
                servers.getAddButton().setEnabled(true);
            }
        }
    }

}
